﻿using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Camera))]
public class CameraController : Singleton<CameraController>
{
    [HideInInspector]
    public bool ApplyFollowX = true;
    [HideInInspector]
    public bool ApplyFollowY = true;

    public float MoveRangeYTop = 10f;
    public float MoveRangeYBottom = -2f;
    public float XRightEdge { get { return transform.position.x + xEdge; } }
    public float YTopEdge { get { return transform.position.y + yEdge; } }
    public float YBottomEdge { get { return transform.position.y - yEdge; } }
    public float CurrentCameraSize { get { return camera.orthographicSize; } }
    new Camera camera;
    float xEdge, yEdge;
    Vector3 startOffest;
    protected override void Awake()
    {
        base.Awake();
        camera = GetComponent<Camera>();
        yEdge = camera.orthographicSize;
        xEdge = yEdge * Screen.width / Screen.height;
    }
    private void Start()
    {
        startOffest = GameManager.Instance.PlayerPlane.transform.position - transform.position;
    }
    private void Update()
    {
        PlaneController player = GameManager.Instance.PlayerPlane;
        Vector3 playerPosition = player.transform.position;
        Vector3 tempOffest = playerPosition - transform.position;
        if (ApplyFollowY)
        {
            if (YTopEdge >= MoveRangeYTop)
            {
                ApplyFollowY = false;
            }
            else if (YBottomEdge <= MoveRangeYBottom)
                ApplyFollowY = false;
            else
            {
                tempOffest.y = startOffest.y;
            }
        }
        else
        {
            if (YTopEdge >= MoveRangeYTop && player.Velocity.y < 0 &&  tempOffest.y < startOffest.y)
            {
                ApplyFollowY = true;
                tempOffest.y = startOffest.y;
            }
            else if (YBottomEdge <= MoveRangeYBottom && player.Velocity.y > 0 && tempOffest.y > startOffest.y)
            {
                ApplyFollowY = true;
                tempOffest.y = startOffest.y;
            }
        }
        if (ApplyFollowX)
            tempOffest.x = startOffest.x;
        transform.position = playerPosition - tempOffest;
    }
}
